// component/special_text/special-text.js
import { 
  _emojiMap,
  _qqEmojiMap
 } from "./emoji";

var TYPE_NONE = -1;
var TYPE_PROJECT = 1;
var TYPE_USER = 2;
var TYPE_BLOG = 3;
var TYPE_TOPIC = 4;
var TYPE_URL = 5;
var TYPE_EMOJI = 6;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    source: {
      type: String,
      observer: function(newVal){
        if(newVal){
          this.traverseSource(newVal);
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    specialTextList: [],
  },

  lifetimes: {
    ready: function(){
      // var source = "123 <a href=\"https://my.oschina.net/u/1272314\" class=\"referer\" target=\"_blank\">@胖达panda</a>  [微笑][撇嘴][色][发呆]:bowtie:😄";
      // var source = "3 <a href=\"https://m/1272314\" class=\"referer\">@胖达panda</a>  [微笑][撇嘴][色][发呆]:bowtie:😄";
      this.traverseSource(this.data.source);
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    traverseSource: function(source){
      var length = source.length;
      var specialText;
      var textStack = "";
      var inlineList = [];
      for (let index = 0; index < length; index++) {
        const char = source.charAt(index);
        textStack += char;
        if(specialText){
          if (!specialText.isEnd(textStack)) {
            specialText.appendContent(char);
          } else {
            // inlineList.push(specialText.finishText());
            specialText.doFinishText();
            inlineList.push(specialText);
            specialText = null;
            textStack = "";
          }
        } else {
          specialText = this.createSpecialText(textStack);
          if(specialText){
            if (textStack.length - specialText.startFlag.length >= 0) {
              textStack = textStack.substring(
                  0, textStack.length - specialText.startFlag.length);
              if (textStack.length > 0) {
                inlineList.push({type: TYPE_NONE, finishText: textStack});
              }
            }
            textStack = "";
          }
        }
      }
      if(specialText){
        specialText.doFinishText(true);
        inlineList.push({type: TYPE_NONE, finishText: specialText.finishText});
      } else if(textStack){
        inlineList.push({type: TYPE_NONE, finishText: textStack});
      }
      this.setData({
        specialTextList: inlineList,
      });
    },
    createSpecialText: function(startFlag){
      var startFlagReg = "<" + ".*" + "[^<>]*?\\s?>(.*?)";
      var position = startFlag.search(startFlagReg);
      if(position >= 0){
        var type = this.getType(startFlag);
        if(type == TYPE_NONE){
          return null;
        } else {
          var endFlag = "</"+"a>";
          var regex = "<a[^<>]*?>";
          var patt = new RegExp(regex,"g");
          var flag = patt.exec(startFlag)[0];
          var that = this;
          var specialText = {
            name: '',
            type: type,
            value: '',
            content: '',
            id: '',
            startFlag: flag,
            endFlag: endFlag,
            finishText: '',
            appendContent: function(char){
              this.content += char; 
            },
            isEnd: function(text){
              if(text.indexOf(endFlag) >= 0){
                if(text.indexOf(endFlag) + endFlag.length == text.length){
                  this.content = text.substring(0, text.length-endFlag.length);
                  return true;
                }
                return false;
              } else {
                return false;
              }
            },
            doFinishText: function(){
              var allText = this.startFlag + this.content + this.endFlag;
              var href = that.getAttrValueFromHtmlTag(allText, ".*", "href");
              var resultText = that.delHtmlTag(allText);
              this.finishText = resultText;
              switch(type){
                case TYPE_PROJECT:
                  this.value = href.substring(href.lastIndexOf("/")+1);//name
                  break;
                case TYPE_USER:
                  this.value = resultText.substring(1);
                  this.id = href.substring(href.lastIndexOf("/") + 1);
                  break;
                case TYPE_TOPIC:
                  this.value = resultText.substring(1, resultText.length - 1);
                  break;
                case TYPE_BLOG:
                  this.id = href.substring(href.lastIndexOf("/") + 1);
                  break;
                case TYPE_URL:
                  this.value = href;
                  break;
              }
            }
          };
          console.log('-- specialText' + specialText);
          return specialText;
        }
      } else if(startFlag.indexOf('[') >= 0){
        var specialText = {
          type: TYPE_EMOJI,
            value: '',
            content: '',
            id: '',
            startFlag: '[',
            endFlag: ']',
            finishText: '',
            loseRight: false,
            appendContent: function(char){
              if(char == ' ' || char == '[' || char == ':'){
                this.finishText = this.content;
                this.type = TYPE_NONE;
                this.loseRight = true;
              } else {
                this.content += char; 
              }
            },
            isEnd: function(text){
              if(text.indexOf(' ') >= 0 || text.indexOf('[') >= 0 || text.indexOf(':') >= 0){
                this.content = text.substring(0, text.length-1);
                this.loseRight = true;
                return true;
              }
              if(text.indexOf(this.endFlag) >= 0){
                if(text.indexOf(this.endFlag) + this.endFlag.length == text.length){
                  this.content = text.substring(0, text.length-this.endFlag.length);
                  return true;
                }
                return false;
              } else {
                return false;
              }
            },
            doFinishText: function(loseRight){
              var allText;
              if(this.loseRight || loseRight){
                allText = this.startFlag + this.content;
              } else {
                allText = this.startFlag + this.content + this.endFlag;
              }
              var name = _qqEmojiMap[allText];
              if(name){
                this.finishText = name;
              } else {
                var regex = "\\[[0-9]\\]|\\[[1-9]{0,2}\\]|\\[[1][0][0-4]\\]";
                var patt = new RegExp(regex,"g");
                var list = patt.exec(startFlag);
                var name;
                if(list){
                  name = list[0];
                }
                if(name){
                  // this.finishText = "smiley_${key.substring(1, key.length-1)}";
                  this.finishText = 'smiley_' + allText.substring(1, allText.length - 1);
                } else {
                  this.type = -1;
                  this.finishText = (this.loseRight || loseRight)? this.startFlag + this.content : allText;
                }
              }
              console.log(this.finishText);
            }
        }
        return specialText;
      } else if(!this.isUrl(startFlag) && startFlag.indexOf(':') >= 0){
        var specialText = {
          type: TYPE_EMOJI,
            value: '',
            content: '',
            id: '',
            startFlag: ':',
            endFlag: ':',
            finishText: '',
            loseRight: false,
            appendContent: function(char){
              if(char == ' ' || char == '['){
                this.finishText = this.content;
                this.type = TYPE_NONE;
                this.loseRight = true;
              } else {
                this.content += char; 
              }
            },
            isEnd: function(text){
              if(text.indexOf(' ') >= 0 || text.indexOf('[') >= 0){
                this.content = text.substring(0, text.length-1);
                this.loseRight = true;
                return true;
              }
              if(text.indexOf(this.endFlag) >= 0){
                if(text.indexOf(this.endFlag) + this.endFlag.length == text.length){
                  this.content = text.substring(0, text.length-this.endFlag.length);
                  return true;
                }
                return false;
              } else {
                return false;
              }
            },
            doFinishText: function(loseRight){
              var allText = this.startFlag + this.content + this.endFlag;
              var name = _emojiMap[allText];
              if(name){
                this.finishText = name;
              } else {
                this.type = TYPE_NONE;
                this.finishText = (this.loseRight || loseRight)? this.startFlag+this.content : allText;
              }
              console.log(this.finishText);
            }
        }
        return specialText;
      }
      return null;
    },
  
    
    getType: function(flag){
      var classType = this.getAttrValueFromHtmlTag(flag, ".*", "class");
      var rel = this.getAttrValueFromHtmlTag(flag, ".*", "rel");
      var href = this.getAttrValueFromHtmlTag(flag, ".*", "href");
      var type = TYPE_NONE;
      if(classType){
        if(classType.indexOf("project") >= 0){
          type = TYPE_PROJECT;
        } else if(classType.indexOf("referer") >= 0){
          type = TYPE_USER;
        }
      } else if(href && href.indexOf("tweet-topic") >= 0){
        type = TYPE_TOPIC;
      } else if(rel || href){
        if(href && href.indexOf("/blog/") >= 0){
          type = TYPE_BLOG;
        } else {
          type = TYPE_URL;
        }
      } else {
        return TYPE_NONE;
      }
      return type;
    },
  
    /// 获取指定HTML标签的指定属性的值
    /// @param source 要匹配的源文本
    /// @param element 标签名称
    /// @param attr 标签的属性名称
    /// @return 属性值列表
    getAttrValueFromHtmlTag: function(source, element, attr) {
      //"<" + ".*" + "[^<>]*?\\s?>(.*?)"
      // *	匹配前面的子表达式零次或多次。
      // +	匹配前面的子表达式一次或多次。
      // ?	匹配前面的子表达式零次或一次。
      // .	匹配除换行符 \n 之外的任何单字符
      // \s 匹配任何空白字符，包括空格、制表符、换页符等等。
      // ()	标记一个子表达式的开始和结束位置。
      var regex = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?(\\s.*)?>";
  //    String regex = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]>";
      var patt = new RegExp(regex,"g");
      var result = patt.exec(source);
      if(result){
        return result[1];
      }
      return result;
    },

    isUrl: function(text){
      var regex = "[a-zA-z]+:";
      // var patt = new RegExp(regex,"g");
      // var result = patt.exec(text);
      return text.search(regex) >= 0;
    },

    delHtmlTag: function(str) {
      return str.replace(/<[^>]+>/g,"");//去掉所有的html标记
    },

    onClick: function(e){
      var dataset = e.currentTarget.dataset;
      var type = dataset.type;
      switch(type){
        case TYPE_PROJECT:
          var id = dataset.id;
          var ident = dataset.value;
          wx.navigateTo({
            url: '/pages/project/detail/detail?ident='+ident+'&type='+type,
          });
          break;
        case TYPE_USER:
          // var id = dataset.id;
          var name = dataset.value;
          wx.navigateTo({
            url: '/pages/user/user?name='+name,
          });
          break;
        case TYPE_TOPIC:
          var id = dataset.id;
          var name = dataset.value;
          wx.navigateTo({
            url: '/pages/topic/topic?id='+id+'&name='+name,
          });
          break;
        
        case TYPE_BLOG:
          var id = dataset.id;
          wx.navigateTo({
            url: '/pages/article/detail/detail?id='+id+'&type='+type,
          });
          break;

        case TYPE_URL:

          break;
      }
    },
  }
})
